package com.example.zqathserver.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
 * HGJT单点登录模拟
 */
@RestController
@RequestMapping("/ssoserver")
public class HGJTController {

    // 模拟存储授权码、访问令牌、刷新令牌
    private static final Map<String, String> authorizationCodes = new HashMap<>();
    private static final Map<String, String> accessTokens = new HashMap<>();
    private static final Map<String, String> refreshTokens = new HashMap<>();

    /**
     * 授权码模式: 获取Authorization Code
     * @param responseType 固定值"code"
     * @param clientId 应用系统的ID
     * @param redirectUri 回调地址
     * @param state CSRF防护的状态参数
     * @param display 移动端类型，可选
     * @return 重定向到redirect_uri，并携带code和state
     */
    @GetMapping("/moc2/authorize")
    public ResponseEntity<?> authorize(
            @RequestParam("response_type") String responseType,
            @RequestParam("client_id") String clientId,
            @RequestParam("redirect_uri") String redirectUri,
            @RequestParam("state") String state,
            @RequestParam(value = "display", required = false) String display) {
        System.out.println("获取Authorization Code");
        if (!"code".equals(responseType)) {
            return ResponseEntity.badRequest().body("Invalid response_type");
        }

        // 生成并保存授权码
        String authorizationCode = generateCode();
        authorizationCodes.put(clientId, authorizationCode);

        // 构建重定向 URL
        String redirectUrl = UriComponentsBuilder.fromUriString(redirectUri)
                .queryParam("code", authorizationCode)
                .queryParam("state", state)
                .build().toUriString();

        // 重定向到 redirect_uri
        return ResponseEntity.status(HttpStatus.FOUND)
                .header(HttpHeaders.LOCATION, redirectUrl)
                .build();
    }

    /**
     * 获取Access Token
     * @param grantType 授权类型，固定为"authorization_code"
     * @param clientId 应用系统的ID
     * @param clientSecret 应用系统的密钥
     * @param code 上一步返回的Authorization Code
     * @param redirectUri 与获取Authorization Code时保持一致
     * @return 返回access_token和refresh_token
     */
    @PostMapping("/moc2/token")
    public ResponseEntity<?> getAccessToken(
            @RequestParam("grant_type") String grantType,
            @RequestParam("client_id") String clientId,
            @RequestParam("client_secret") String clientSecret,
            @RequestParam("code") String code,
            @RequestParam("redirect_uri") String redirectUri) {
        System.out.println("获取Access Token");
//        if (!"code".equals(grantType))     {
//            return ResponseEntity.badRequest().body("Invalid grant_type");
//        }
//
//        // 验证授权码
//        if (!isValidAuthorizationCode(clientId, code)) {
//            return ResponseEntity.badRequest().body("Invalid or expired authorization code");
//        }
//
//        // 生成并保存访问令牌和刷新令牌
//        String accessToken = generateToken("AC");
//        String refreshToken = generateToken("RT");
//        accessTokens.put(clientId, accessToken);
//        refreshTokens.put(clientId, refreshToken);

        // 返回令牌信息
        Map<String, Object> response = new HashMap<>();
        response.put("ret", "0");
        response.put("access_token", "accessToken");
        response.put("refresh_token", "refreshToken");
        response.put("expires_in", 864000);  // 10天有效期

        return ResponseEntity.ok(response);
    }

    /**
     * 获取用户信息，需要传入access_token
     * @param accessToken 颁发的访问令牌
     * @return 用户信息
     */
    @GetMapping("/moc2/me")
    public ResponseEntity<?> getOpenid(
            @RequestParam("access_token") String accessToken) {
        System.out.println("获取openid");
//        // 验证访问令牌
//        if (!isValidAccessToken(accessToken)) {
//            return ResponseEntity.badRequest().body("Invalid access_token");
//        }
        Map<String, Object> response = new HashMap<>();
        response.put("ret", "0");
        response.put("openid", "openid");
  
        // 返回用户信息
        return ResponseEntity.ok(response);
    }

    /**
     * 获取用户信息（模拟接口）
     * @param accessToken 颁发的访问令牌
     * @param consumerKey 应用系统ID
     * @param openid 用户的OpenID
     * @return 用户信息或错误信息
     */
    @GetMapping("/user/info")
    public ResponseEntity<Map<String, Object>> getUserInfo(
            @RequestParam("access_token") String accessToken,
            @RequestParam("oauth_consumer_key") String consumerKey,
            @RequestParam("openid") String openid) {
        System.out.println("获取用户信息");
//        // 验证参数
//        if (isValidAccessToken(accessToken) && isValidConsumerKey(consumerKey) && isValidOpenId(openid)) {
            // 构建成功响应
            return ResponseEntity.ok(buildSuccessResponse(openid));
//        } else {
//            // 构建错误响应
//            return ResponseEntity.badRequest().body(buildErrorResponse("Invalid request parameters"));
//        }
    }

    // ====================== 辅助方法 =========================

    // 生成唯一代码
    private String generateCode() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    // 生成令牌
    private String generateToken(String prefix) {
        return prefix + "-" + UUID.randomUUID().toString().replace("-", "");
    }

    // 验证授权码
    private boolean isValidAuthorizationCode(String clientId, String code) {
        return code != null && code.equals(authorizationCodes.get(clientId));
    }

    // 验证access_token
    private boolean isValidAccessToken(String accessToken) {
        return accessTokens.containsValue(accessToken);
    }

    // 验证consumer_key
    private boolean isValidConsumerKey(String consumerKey) {
        return "oauth_consumer_key".equals(consumerKey);
    }

    // 验证openid
    private boolean isValidOpenId(String openid) {
        return openid != null && !openid.isEmpty();
    }

    // 构建用户信息
    private Map<String, Object> buildUserDetails(String openid) {
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("userno", "yaojx1981");// yaojx1981  //yaojiaxin123 // hyf //yaojx19811981
        userInfo.put("uid", "uid");
        userInfo.put("cn", "John Doe");
        userInfo.put("mail", "john.doe@example.com");
        userInfo.put("deptment", "001");
        userInfo.put("deptmentTitle", "IT Department");
        userInfo.put("businessCategory", "User Password");
        userInfo.put("headship", "Manager");
        userInfo.put("description", "User description");
        userInfo.put("pwdexpirationtime", "2025-12-31");
        userInfo.put("accountactiveday", "2023-09-25");
        userInfo.put("fixphone", "123-456-7890");
        userInfo.put("accountstatu", "Online");
        userInfo.put("externalAuth", "ldap");
        userInfo.put("qqId", "123456789");
        userInfo.put("timestamp", "2024-09-25 12:34:56");
        userInfo.put("account", "business_account");
        userInfo.put("pwd", "encrypted_password");
        return userInfo;
    }

    // 构建成功响应
    private Map<String, Object> buildSuccessResponse(String openid) {
        Map<String, Object> response = new HashMap<>();
        response.put("ret", "0");
        response.put("msg", "");
        response.put("userinfo", buildUserDetails(openid));
        return response;
    }

    // 构建错误响应
    private Map<String, Object> buildErrorResponse(String errorMsg) {
        Map<String, Object> errorResponse = new HashMap<>();
        errorResponse.put("ret", "1");
        errorResponse.put("msg", errorMsg);
        return errorResponse;
    }
}



